package com.srwl.mytx.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.activity.BaseActivity;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.Message;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 系统通知适配器
 * <p>
 */
public class TransferAuthorityNotifyAdapter extends RecyclerView.Adapter<TransferAuthorityNotifyAdapter.TransferAuthorityHolder> {
    private static final String TAG = "TransferAuthority";
    private Context context;
    private List<Message> messageList;
    private NotifyMessageInteractionListener listener;


    public TransferAuthorityNotifyAdapter(Context context, List<Message> messageList, NotifyMessageInteractionListener listener) {
        this.context = context;
        this.messageList = messageList;
        this.listener = listener;
    }

    @Override
    public int getItemViewType(int position) {
        return messageList.get(position).getSubType();
    }

    @NonNull
    @Override
    public TransferAuthorityHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //展示主题新管理员的信息
        View newMangerView = LayoutInflater.from(context).inflate(R.layout.notify_message_new_manger_item_layout, parent, false);
        return new TransferAuthorityHolder(newMangerView);
    }

    @Override
    public void onBindViewHolder(@NonNull final TransferAuthorityHolder viewHolder, int position) {
        Message notify = messageList.get(position);
        Integer type = notify.getSubType();
        if (type == null) {
            return;
        }
        if (type == Constant.APPLY_AUTHORITY_TRANSFER) {
            handleTransferAuthority(viewHolder, notify);
        } else if (type == Constant.ACCEPT_AUTHORITY_TRANSFER) {
            String extraData = notify.getExtraData();
            if (TextUtils.isEmpty(extraData)) return;
            Topic topic = JSONObject.parseObject(extraData).toJavaObject(Topic.class);
            //Glide.with(context).load(Utils.getIconUrlScale20(topic)).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_avatar);
            GlideLoadUtils.glideLoad(context, Utils.getIconUrlScale20(topic), viewHolder.iv_avatar);
            viewHolder.tv_topicTitle.setText(topic.getTitle());
            viewHolder.tv_update_time.setText(DateUtils.getTimestampString(notify.getCreated()));
            viewHolder.iv_avatar.setOnClickListener(v -> toTopicDetail(topic));
            viewHolder.tv_topicTitle.setOnClickListener(v -> toTopicDetail(topic));
            viewHolder.tv_content.setText(notify.getContent());
            viewHolder.btn_accept.setVisibility(View.GONE);
            viewHolder.btn_refuse.setVisibility(View.GONE);
        }
    }


    /**
     * 处理权限移交的通知信息
     *
     * @param viewHolder
     * @param notify
     */
    private void handleTransferAuthority(@NonNull TransferAuthorityHolder viewHolder, Message notify) {
        //获取展示的消息
        String extraData = notify.getExtraData();
        if (TextUtils.isEmpty(extraData)) return;
        Topic topic = JSONObject.parseObject(extraData).toJavaObject(Topic.class);
        //Glide.with(context).load(Utils.getIconUrlScale20(topic)).diskCacheStrategy(DiskCacheStrategy.ALL).into(viewHolder.iv_avatar);
        GlideLoadUtils.glideLoad(context, Utils.getIconUrlScale20(topic), viewHolder.iv_avatar);
        viewHolder.tv_topicTitle.setText(topic.getTitle());
        viewHolder.tv_update_time.setText(DateUtils.getTimestampString(notify.getCreated()));
        // viewHolder.tv_old_manger.setOnClickListener(v -> contact(notify.getFromId()));
        viewHolder.iv_avatar.setOnClickListener(v -> toTopicDetail(topic));
        viewHolder.tv_topicTitle.setOnClickListener(v -> toTopicDetail(topic));
        viewHolder.tv_content.setText(notify.getContent());
        Integer state = notify.getState();
        if (state == null) {
            return;
        }
        if (state == Constant.INVITE_MESSAGE_STATUS_APPLY) {
            viewHolder.btn_accept.setVisibility(View.VISIBLE);
            viewHolder.btn_accept.setEnabled(true);
            viewHolder.btn_refuse.setVisibility(View.VISIBLE);
            viewHolder.btn_refuse.setEnabled(true);
            viewHolder.btn_accept.setOnClickListener(v -> showAcceptDialog(notify, topic));
            viewHolder.btn_refuse.setOnClickListener(v -> showRefuseDialog(notify, topic));
        } else if (state == Constant.INVITE_MESSAGE_STATUS_AGREED) {
            viewHolder.btn_accept.setVisibility(View.VISIBLE);
            viewHolder.btn_accept.setEnabled(false);
            viewHolder.btn_accept.setText("已接受");
            viewHolder.btn_accept.setBackgroundResource(R.drawable.tx_btn_shape_gray);
            viewHolder.btn_refuse.setVisibility(View.GONE);
        } else if (state == Constant.INVITE_MESSAGE_STATUS_REFUSED) {
            viewHolder.btn_refuse.setVisibility(View.VISIBLE);
            viewHolder.btn_refuse.setEnabled(false);
            viewHolder.btn_refuse.setText("已拒绝");
            viewHolder.btn_refuse.setBackgroundResource(R.drawable.tx_btn_shape_gray);
            viewHolder.btn_accept.setVisibility(View.GONE);
        }
    }

    private void showAcceptDialog(Message notify, Topic topic) {

        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "接受[ " + topic.getTitle() + " ]的管理权限", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                accept(notify, topic);
            }
        });
        dialog.show();
    }

    private void accept(Message notify, Topic topic) {
        if (!Helper.getInstance().isNetworkConnected()) {
            ((BaseActivity) context).showToast_v1(context.getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .acceptTopicAuthorityTransfer(topic.getId())
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (result.getStatus() == Constant.NO_AUTHORITY) {
                            }
                            return;
                        }
                        //更新通知消息的状态
                        notify.setState(Constant.INVITE_MESSAGE_STATUS_AGREED);
                        DBManager.getInstance().getDaoSession().getMessageDao().update(notify);
                        notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        t.printStackTrace();
                    }
                });
    }

    private void showRefuseDialog(Message notify, Topic topic) {
        ConfirmDialog dialog = new ConfirmDialog(context, "提示", "拒绝[ " + topic.getTitle() + " ]的管理权限", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                //拒绝权限，直接更新本地消息状态，并没有请求后端，权限移交发起人并不知道被拒绝了，以后如果有必要，再请求后端，
                //更新通知消息的状态
                notify.setState(Constant.INVITE_MESSAGE_STATUS_REFUSED);
                DBManager.getInstance().getDaoSession().getMessageDao().update(notify);
                notifyDataSetChanged();
            }
        });
        dialog.show();
    }


    @Override
    public int getItemCount() {
        return messageList.size();
    }


    public class TransferAuthorityHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_avatar)
        ImageView iv_avatar;
        @BindView(R.id.tv_topic_title)
        TextView tv_topicTitle;
        @BindView(R.id.tv_content)
        TextView tv_content;
        @BindView(R.id.tv_update_time)
        TextView tv_update_time;
        //        @BindView(R.id.tv_old_manger)
//        TextView tv_old_manger;
        @BindView(R.id.btn_accept)
        Button btn_accept;
        @BindView(R.id.btn_refuse)
        Button btn_refuse;

        public TransferAuthorityHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    private void contact(String targetUserId) {
        User userInfo = Helper.getInstance().queryUserInfoById(targetUserId);
        if (userInfo != null) {
            context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
        } else {
            getFullUserInfo(targetUserId);
        }
    }


    private void getFullUserInfo(String userId) {

        RetrofitManager.getInstance().createRequest(UserService.class)
                .getUserInfo(userId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            // showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User userInfo = object.toJavaObject(User.class);
                        userInfo.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(userInfo);
                        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        // showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });


    }

    /**
     * 跳转到主题详情
     */
    private void toTopicDetail(Topic topic) {
        TopicDetailsActivity.startActivity(context, topic.getId());
    }

}
